package com.cqhz.quwan.util.service

import android.app.DownloadManager
import android.app.Service
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.os.IBinder
import android.support.v4.content.FileProvider
import com.cqhz.quwan.common.KeyContract
import com.cqhz.quwan.util.deleteFile
import java.io.File

/**
 * 下载服务
 * Created by Guojing on 2018/10/11.
 */
class DownloadService : Service() {

    override fun onBind(intent: Intent): IBinder? {
        return null
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        if (intent != null) {
            val downloadUrl = intent.extras!!.getString(DOWNLOAD_URL)
            if (downloadUrl != null) {
                // 注册下载完成广播
                val completeReceiver = DownloadCompleteReceiver()
                registerReceiver(completeReceiver, IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE))
                Thread(DownloadRunnable(downloadUrl)).start()// 下载
            }
        }
        return super.onStartCommand(intent, flags, startId)
    }

    /**
     * 下载
     */
    internal inner class DownloadRunnable(private val mDownloadUrl: String) : Runnable {

        override fun run() {
            startDownload()
        }

        // 开始下载
        private fun startDownload() {
            val folder = Environment.getExternalStoragePublicDirectory(DOWNLOAD_FOLDER_NAME)
            if (!folder.exists() || !folder.isDirectory) {
                folder.mkdirs()
            }

            // 删除已存在文件
            val apkFilePath = StringBuilder(Environment.getExternalStorageDirectory().absolutePath)
                    .append(File.separator).append(DOWNLOAD_FOLDER_NAME).append(File.separator)
                    .append(DOWNLOAD_FILE_NAME).toString()
            File(apkFilePath).deleteFile()

            val manager = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
            val request = DownloadManager.Request(Uri.parse(mDownloadUrl))
            request.setMimeType("application/vnd.android.package-archive")
            // 存储的目录
            request.setDestinationInExternalPublicDir(DOWNLOAD_FOLDER_NAME, DOWNLOAD_FILE_NAME)
            // 设定下载
            request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI or DownloadManager.Request.NETWORK_MOBILE)
            request.setTitle("下载天天趣玩")
            request.setVisibleInDownloadsUi(true)
            manager.enqueue(request)
        }
    }

    /**
     * 下载完成
     */
    internal inner class DownloadCompleteReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val completeDownloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1)
            if (intent.action === DownloadManager.ACTION_DOWNLOAD_COMPLETE) {
                checkStatus(context, completeDownloadId)
            }
        }

        private fun checkStatus(context: Context, completeDownloadId: Long) {
            val mManager = context.getSystemService(Service.DOWNLOAD_SERVICE) as DownloadManager
            val query = DownloadManager.Query()
            query.setFilterById(completeDownloadId)
            val cursor = mManager.query(query)
            if (cursor.moveToFirst()) {
                val status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS))

                when (status) {
                    DownloadManager.STATUS_RUNNING -> {
                    }

                    DownloadManager.STATUS_SUCCESSFUL -> {
                        installApk(context)

                        // 停止下载Service
                        this@DownloadService.stopSelf()
                    }

                    else -> {
                    }
                }
            }
            cursor.close()
        }
    }

    companion object {
        val DOWNLOAD_URL = "download_url"
        val DOWNLOAD_FOLDER_NAME = "ttquwan"
        val DOWNLOAD_FILE_NAME = "ttquwan.apk"

        /**
         * 安装apk
         *
         * @param context
         */
        fun installApk(context: Context) {
            val apkFilePath = StringBuilder(Environment.getExternalStorageDirectory().absolutePath)
                    .append(File.separator).append(DOWNLOAD_FOLDER_NAME).append(File.separator)
                    .append(DOWNLOAD_FILE_NAME).toString()
            val apkFile = File(apkFilePath)
            val intent = Intent(Intent.ACTION_VIEW)

            // 判读版本是否在7.0以上
            if (Build.VERSION.SDK_INT >= 24) {
                val apkUri = FileProvider.getUriForFile(context, KeyContract.FILE_PROVIDER, apkFile)// 通过FileProvider创建一个content类型的Uri
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)// 添加这一句表示对目标应用临时授权该Uri所代表的文件
                intent.setDataAndType(apkUri, "application/vnd.android.package-archive")
            } else {
                intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive")
            }
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            context.startActivity(intent)
        }
    }
}
